import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  Progress,
  Tag,
  Typography,
  Space,
  Button,
  Select,
  DatePicker,
  Alert,
  List,
  Avatar,
  Tooltip,
  Badge,
  Divider,
  Tabs,
  message,
  Empty,
  Spin,
  Timeline,
  Modal,
  Descriptions,
  Steps,
  Collapse,
} from "antd";
import {
  UserOutlined,
  TeamOutlined,
  BookOutlined,
  TrophyOutlined,
  RiseOutlined,
  FallOutlined,
  ClockCircleOutlined,
  FireOutlined,
  EyeOutlined,
  DownloadOutlined,
  PrinterOutlined,
  ReloadOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  StarOutlined,
  GlobalOutlined,
  DashboardOutlined,
  BellOutlined,
  SecurityScanOutlined,
  BugOutlined,
  AlertOutlined,
  SafetyOutlined,
  RobotOutlined,
  SyncOutlined,
  LoadingOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  ExclamationCircleFilled,
  InfoCircleFilled,
} from "@ant-design/icons";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  AreaChart,
  Area,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from "recharts";
import styled from "styled-components";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { adminAPI } from "../../../services/api";
import { useUser } from "../../../contexts/UserContext";

dayjs.extend(relativeTime);

const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;
const { Step } = Steps;
const { Panel } = Collapse;

// 类型定义
interface RiskBehavior {
  id: string;
  userId: string;
  userName: string;
  userRole: string;
  behaviorType: "login_anomaly" | "data_access" | "system_abuse" | "content_violation" | "performance_issue";
  riskLevel: "low" | "medium" | "high" | "critical";
  description: string;
  timestamp: Date;
  status: "pending" | "investigating" | "resolved" | "false_positive";
  evidence: string[];
  aiConfidence: number;
  recommendedAction: string;
}

interface SystemIssue {
  id: string;
  type: "performance" | "security" | "database" | "network" | "application";
  severity: "low" | "medium" | "high" | "critical";
  title: string;
  description: string;
  timestamp: Date;
  status: "detected" | "investigating" | "resolving" | "resolved";
  affectedComponents: string[];
  impact: string;
  aiAnalysis: string;
  resolution: string;
}

interface AIMonitoringStats {
  totalScans: number;
  threatsDetected: number;
  falsePositives: number;
  systemHealth: number;
  lastScanTime: Date;
  scanFrequency: string;
  aiAccuracy: number;
  responseTime: number;
}

interface SecurityMetrics {
  loginAttempts: Array<{ date: string; attempts: number; failed: number; suspicious: number }>;
  dataAccessPatterns: Array<{ userType: string; accessCount: number; riskScore: number }>;
  systemPerformance: Array<{ time: string; cpu: number; memory: number; disk: number; network: number }>;
  threatDistribution: Array<{ type: string; count: number; percentage: number }>;
}

const MonitoringContainer = styled.div`
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  .ant-card-head {
    border-bottom: 1px solid #f0f0f0;
    background: linear-gradient(135deg, #fafafa 0%, #fff 100%);
    border-radius: 12px 12px 0 0;
  }

  .ant-card-head-title {
    font-weight: 600;
    font-size: 16px;
    color: #262626;
  }
`;

const MetricCard = styled(Card)`
  text-align: center;
  border-radius: 12px;
  background: linear-gradient(135deg, #fff 0%, #fafafa 100%);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  .metric-content {
    padding: 20px;
  }

  .metric-icon {
    font-size: 32px;
    margin-bottom: 12px;
  }

  .metric-value {
    font-size: 28px;
    font-weight: bold;
    color: #262626;
    margin-bottom: 8px;
  }

  .metric-label {
    font-size: 14px;
    color: #8c8c8c;
    margin-bottom: 8px;
  }

  .metric-trend {
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }
`;

const RiskLevelTag = styled(Tag)`
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 8px;
`;

const AIAnalysisCard = styled(Card)`
  background: linear-gradient(135deg, #f6ffed 0%, #fff 100%);
  border: 1px solid #b7eb8f;
  border-radius: 12px;
  margin-bottom: 16px;

  .ant-card-head {
    background: linear-gradient(135deg, #f6ffed 0%, #fff 100%);
    border-bottom: 1px solid #b7eb8f;
  }

  .ant-card-head-title {
    color: #52c41a;
    font-weight: 600;
  }
`;

const ThreatCard = styled(Card)`
  background: linear-gradient(135deg, #fff2f0 0%, #fff 100%);
  border: 1px solid #ffccc7;
  border-radius: 12px;
  margin-bottom: 16px;

  .ant-card-head {
    background: linear-gradient(135deg, #fff2f0 0%, #fff 100%);
    border-bottom: 1px solid #ffccc7;
  }

  .ant-card-head-title {
    color: #ff4d4f;
    font-weight: 600;
  }
`;

const AdminAIMonitoring: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [scanning, setScanning] = useState(false);
  const [stats, setStats] = useState<AIMonitoringStats>({
    totalScans: 0,
    threatsDetected: 0,
    falsePositives: 0,
    systemHealth: 0,
    lastScanTime: new Date(),
    scanFrequency: "每5分钟",
    aiAccuracy: 0,
    responseTime: 0,
  });
  const [riskBehaviors, setRiskBehaviors] = useState<RiskBehavior[]>([]);
  const [systemIssues, setSystemIssues] = useState<SystemIssue[]>([]);
  const [securityMetrics, setSecurityMetrics] = useState<SecurityMetrics>({
    loginAttempts: [],
    dataAccessPatterns: [],
    systemPerformance: [],
    threatDistribution: [],
  });
  const [selectedRisk, setSelectedRisk] = useState<RiskBehavior | null>(null);
  const [selectedIssue, setSelectedIssue] = useState<SystemIssue | null>(null);
  const [riskModalVisible, setRiskModalVisible] = useState(false);
  const [issueModalVisible, setIssueModalVisible] = useState(false);

  // 生成模拟数据
  const generateMockData = () => {
    // 生成风险行为数据
    const behaviorTypes = ["login_anomaly", "data_access", "system_abuse", "content_violation", "performance_issue"];
    const riskLevels = ["low", "medium", "high", "critical"];
    const statuses = ["pending", "investigating", "resolved", "false_positive"];
    
    const mockRiskBehaviors: RiskBehavior[] = Array.from({ length: 15 }, (_, index) => {
      const behaviorType = behaviorTypes[Math.floor(Math.random() * behaviorTypes.length)];
      const riskLevel = riskLevels[Math.floor(Math.random() * riskLevels.length)];
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      
      const descriptions = {
        login_anomaly: [
          "异常登录尝试：用户从多个不同IP地址登录",
          "登录频率异常：短时间内多次登录失败",
          "地理位置异常：从非常用地区登录",
          "设备指纹异常：使用未知设备登录",
          "时间模式异常：在非正常时间登录"
        ],
        data_access: [
          "异常数据访问：访问超出权限范围的数据",
          "批量数据下载：短时间内下载大量数据",
          "敏感数据访问：访问高敏感度数据",
          "数据导出异常：频繁导出数据文件",
          "跨部门数据访问：访问其他部门数据"
        ],
        system_abuse: [
          "系统资源滥用：占用过多CPU和内存",
          "API调用异常：频繁调用系统API",
          "自动化脚本：检测到自动化操作",
          "权限提升尝试：尝试获取更高权限",
          "系统配置修改：未经授权的配置更改"
        ],
        content_violation: [
          "不当内容发布：发布违反规定的内容",
          "垃圾信息：发布大量垃圾信息",
          "版权侵犯：上传侵犯版权的内容",
          "恶意链接：发布恶意链接",
          "不当评论：发布不当评论内容"
        ],
        performance_issue: [
          "系统响应缓慢：用户报告系统响应慢",
          "数据库连接异常：数据库连接超时",
          "内存泄漏：检测到内存使用异常",
          "网络延迟：网络连接不稳定",
          "服务异常：关键服务响应异常"
        ]
      };

      const recommendedActions = {
        low: ["监控用户行为", "发送提醒通知", "记录日志"],
        medium: ["限制用户权限", "要求身份验证", "启动调查"],
        high: ["临时封禁账户", "立即通知管理员", "启动应急响应"],
        critical: ["立即封禁账户", "启动安全事件响应", "通知安全团队"]
      };

      return {
        id: `risk_${index + 1}`,
        userId: `user_${Math.floor(Math.random() * 1000)}`,
        userName: `用户${index + 1}`,
        userRole: ["学生", "教师", "管理员"][Math.floor(Math.random() * 3)],
        behaviorType: behaviorType as any,
        riskLevel: riskLevel as any,
        description: descriptions[behaviorType as keyof typeof descriptions][Math.floor(Math.random() * descriptions[behaviorType as keyof typeof descriptions].length)],
        timestamp: dayjs().subtract(Math.floor(Math.random() * 24), "hours").toDate(),
        status: status as any,
        evidence: [
          "IP地址记录",
          "用户行为日志",
          "系统访问记录",
          "时间戳分析"
        ].slice(0, Math.floor(Math.random() * 3) + 2),
        aiConfidence: Math.floor(Math.random() * 30) + 70,
        recommendedAction: recommendedActions[riskLevel as keyof typeof recommendedActions][Math.floor(Math.random() * recommendedActions[riskLevel as keyof typeof recommendedActions].length)]
      };
    });

    // 生成系统问题数据
    const issueTypes = ["performance", "security", "database", "network", "application"];
    const severities = ["low", "medium", "high", "critical"];
    const issueStatuses = ["detected", "investigating", "resolving", "resolved"];
    
    const mockSystemIssues: SystemIssue[] = Array.from({ length: 8 }, (_, index) => {
      const issueType = issueTypes[Math.floor(Math.random() * issueTypes.length)];
      const severity = severities[Math.floor(Math.random() * severities.length)];
      const status = issueStatuses[Math.floor(Math.random() * issueStatuses.length)];
      
      const issueTitles = {
        performance: [
          "系统响应时间异常",
          "CPU使用率过高",
          "内存使用率异常",
          "磁盘空间不足",
          "网络带宽占用过高"
        ],
        security: [
          "检测到可疑登录尝试",
          "防火墙规则异常",
          "SSL证书即将过期",
          "安全漏洞扫描发现",
          "异常网络流量"
        ],
        database: [
          "数据库连接池耗尽",
          "慢查询检测",
          "数据库死锁",
          "备份失败",
          "索引碎片化严重"
        ],
        network: [
          "网络延迟异常",
          "DNS解析失败",
          "网络丢包严重",
          "带宽使用异常",
          "网络设备故障"
        ],
        application: [
          "应用服务异常",
          "API响应超时",
          "缓存服务故障",
          "消息队列阻塞",
          "第三方服务异常"
        ]
      };

      const aiAnalyses = [
        "AI分析显示这是正常的系统波动，建议继续监控",
        "检测到潜在的性能瓶颈，建议优化数据库查询",
        "安全扫描发现可疑活动，建议立即调查",
        "系统负载正常，但建议增加监控频率",
        "网络连接稳定，无需立即干预"
      ];

      return {
        id: `issue_${index + 1}`,
        type: issueType as any,
        severity: severity as any,
        title: issueTitles[issueType as keyof typeof issueTitles][Math.floor(Math.random() * issueTitles[issueType as keyof typeof issueTitles].length)],
        description: `系统检测到${issueType}相关问题，需要关注和处理。`,
        timestamp: dayjs().subtract(Math.floor(Math.random() * 12), "hours").toDate(),
        status: status as any,
        affectedComponents: ["用户服务", "数据库", "缓存", "文件存储", "消息队列"].slice(0, Math.floor(Math.random() * 3) + 1),
        impact: ["低影响", "中等影响", "高影响", "严重影响"][Math.floor(Math.random() * 4)],
        aiAnalysis: aiAnalyses[Math.floor(Math.random() * aiAnalyses.length)],
        resolution: status === "resolved" ? "问题已解决，系统恢复正常运行" : "正在处理中..."
      };
    });

    // 生成安全指标数据
    const mockSecurityMetrics: SecurityMetrics = {
      loginAttempts: Array.from({ length: 24 }, (_: any, i: number) => ({
        date: dayjs().subtract(23 - i, "hours").format("HH:00"),
        attempts: Math.floor(Math.random() * 100) + 50,
        failed: Math.floor(Math.random() * 20) + 5,
        suspicious: Math.floor(Math.random() * 10) + 1,
      })),
      dataAccessPatterns: [
        { userType: "学生", accessCount: 1250, riskScore: 15 },
        { userType: "教师", accessCount: 890, riskScore: 25 },
        { userType: "管理员", accessCount: 320, riskScore: 45 },
        { userType: "访客", accessCount: 180, riskScore: 60 },
      ],
      systemPerformance: Array.from({ length: 24 }, (_: any, i: number) => ({
        time: dayjs().subtract(23 - i, "hours").format("HH:00"),
        cpu: Math.floor(Math.random() * 30) + 40,
        memory: Math.floor(Math.random() * 20) + 60,
        disk: Math.floor(Math.random() * 15) + 25,
        network: Math.floor(Math.random() * 40) + 30,
      })),
      threatDistribution: [
        { type: "登录异常", count: 45, percentage: 35 },
        { type: "数据访问异常", count: 28, percentage: 22 },
        { type: "系统滥用", count: 23, percentage: 18 },
        { type: "内容违规", count: 18, percentage: 14 },
        { type: "性能问题", count: 15, percentage: 11 },
      ],
    };

    // 生成统计指标
    const mockStats: AIMonitoringStats = {
      totalScans: 1247,
      threatsDetected: 129,
      falsePositives: 12,
      systemHealth: 96.5,
      lastScanTime: dayjs().subtract(5, "minutes").toDate(),
      scanFrequency: "每5分钟",
      aiAccuracy: 94.2,
      responseTime: 2.3,
    };

    setStats(mockStats);
    setRiskBehaviors(mockRiskBehaviors);
    setSystemIssues(mockSystemIssues);
    setSecurityMetrics(mockSecurityMetrics);
  };

  // 模拟AI扫描
  const performAIScan = async () => {
    setScanning(true);
    message.loading("AI正在扫描系统...", 0);
    
    // 模拟扫描过程
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 更新数据
    generateMockData();
    
    setScanning(false);
    message.destroy();
    message.success("AI扫描完成！发现新的安全威胁和系统问题");
  };

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      generateMockData();
    } catch (error) {
      message.error("加载数据失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 渲染统计指标
  const renderMetrics = () => (
    <Row gutter={[16, 16]}>
      <Col xs={24} sm={12} lg={6}>
        <MetricCard>
          <div className="metric-content">
            <div className="metric-icon" style={{ color: "#1890ff" }}>
              <SecurityScanOutlined />
            </div>
            <div className="metric-value">{stats.totalScans}</div>
            <div className="metric-label">总扫描次数</div>
            <div className="metric-trend">
              <RiseOutlined style={{ color: "#52c41a" }} />
              <span style={{ color: "#52c41a" }}>+12.5%</span>
            </div>
          </div>
        </MetricCard>
      </Col>
      <Col xs={24} sm={12} lg={6}>
        <MetricCard>
          <div className="metric-content">
            <div className="metric-icon" style={{ color: "#ff4d4f" }}>
              <AlertOutlined />
            </div>
            <div className="metric-value">{stats.threatsDetected}</div>
            <div className="metric-label">检测到威胁</div>
            <div className="metric-trend">
              <FallOutlined style={{ color: "#52c41a" }} />
              <span style={{ color: "#52c41a" }}>-8.3%</span>
            </div>
          </div>
        </MetricCard>
      </Col>
      <Col xs={24} sm={12} lg={6}>
        <MetricCard>
          <div className="metric-content">
            <div className="metric-icon" style={{ color: "#52c41a" }}>
              <SafetyOutlined />
            </div>
            <div className="metric-value">{stats.systemHealth}%</div>
            <div className="metric-label">系统健康度</div>
            <div className="metric-trend">
              <RiseOutlined style={{ color: "#52c41a" }} />
              <span style={{ color: "#52c41a" }}>+2.1%</span>
            </div>
          </div>
        </MetricCard>
      </Col>
      <Col xs={24} sm={12} lg={6}>
        <MetricCard>
          <div className="metric-content">
            <div className="metric-icon" style={{ color: "#722ed1" }}>
              <RobotOutlined />
            </div>
            <div className="metric-value">{stats.aiAccuracy}%</div>
            <div className="metric-label">AI准确率</div>
            <div className="metric-trend">
              <RiseOutlined style={{ color: "#52c41a" }} />
              <span style={{ color: "#52c41a" }}>+1.8%</span>
            </div>
          </div>
        </MetricCard>
      </Col>
    </Row>
  );

  // 渲染风险行为表格
  const renderRiskBehaviorsTable = () => {
    const columns = [
      {
        title: "用户",
        dataIndex: "userName",
        key: "userName",
        render: (text: string, record: RiskBehavior) => (
          <Space>
            <Avatar size="small" icon={<UserOutlined />} />
            <div>
              <div>{text}</div>
              <Text type="secondary" style={{ fontSize: "12px" }}>
                {record.userRole}
              </Text>
            </div>
          </Space>
        ),
      },
      {
        title: "行为类型",
        dataIndex: "behaviorType",
        key: "behaviorType",
        render: (type: string) => {
          const typeMap = {
            login_anomaly: { text: "登录异常", color: "#ff4d4f" },
            data_access: { text: "数据访问", color: "#fa8c16" },
            system_abuse: { text: "系统滥用", color: "#eb2f96" },
            content_violation: { text: "内容违规", color: "#722ed1" },
            performance_issue: { text: "性能问题", color: "#13c2c2" },
          };
          const config = typeMap[type as keyof typeof typeMap] || { text: type, color: "default" };
          return <Tag color={config.color}>{config.text}</Tag>;
        },
      },
      {
        title: "风险等级",
        dataIndex: "riskLevel",
        key: "riskLevel",
        render: (level: string) => {
          const colorMap = {
            low: "green",
            medium: "orange",
            high: "red",
            critical: "purple",
          };
          return (
            <RiskLevelTag color={colorMap[level as keyof typeof colorMap]}>
              {level.toUpperCase()}
            </RiskLevelTag>
          );
        },
      },
      {
        title: "AI置信度",
        dataIndex: "aiConfidence",
        key: "aiConfidence",
        render: (confidence: number) => (
          <Progress
            percent={confidence}
            size="small"
            status={confidence > 90 ? "success" : confidence > 70 ? "normal" : "exception"}
            showInfo={false}
          />
        ),
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        render: (status: string) => {
          const statusMap = {
            pending: { text: "待处理", color: "default" },
            investigating: { text: "调查中", color: "processing" },
            resolved: { text: "已解决", color: "success" },
            false_positive: { text: "误报", color: "warning" },
          };
          const config = statusMap[status as keyof typeof statusMap] || { text: status, color: "default" };
          return <Badge status={config.color as any} text={config.text} />;
        },
      },
      {
        title: "时间",
        dataIndex: "timestamp",
        key: "timestamp",
        render: (timestamp: Date) => dayjs(timestamp).format("MM-DD HH:mm"),
      },
      {
        title: "操作",
        key: "action",
        render: (_: any, record: RiskBehavior) => (
          <Button
            type="link"
            size="small"
            onClick={() => {
              setSelectedRisk(record);
              setRiskModalVisible(true);
            }}
          >
            查看详情
          </Button>
        ),
      },
    ];

    return (
      <Table
        columns={columns}
        dataSource={riskBehaviors}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        size="small"
      />
    );
  };

  // 渲染系统问题表格
  const renderSystemIssuesTable = () => {
    const columns = [
      {
        title: "问题类型",
        dataIndex: "type",
        key: "type",
        render: (type: string) => {
          const typeMap = {
            performance: { text: "性能问题", color: "#ff4d4f" },
            security: { text: "安全问题", color: "#fa8c16" },
            database: { text: "数据库", color: "#eb2f96" },
            network: { text: "网络问题", color: "#722ed1" },
            application: { text: "应用问题", color: "#13c2c2" },
          };
          const config = typeMap[type as keyof typeof typeMap];
          return <Tag color={config.color}>{config.text}</Tag>;
        },
      },
      {
        title: "严重程度",
        dataIndex: "severity",
        key: "severity",
        render: (severity: string) => {
          const colorMap = {
            low: "green",
            medium: "orange",
            high: "red",
            critical: "purple",
          };
          return (
            <RiskLevelTag color={colorMap[severity as keyof typeof colorMap]}>
              {severity.toUpperCase()}
            </RiskLevelTag>
          );
        },
      },
      {
        title: "标题",
        dataIndex: "title",
        key: "title",
        ellipsis: true,
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        render: (status: string) => {
          const statusMap = {
            detected: { text: "已检测", color: "default" },
            investigating: { text: "调查中", color: "processing" },
            resolving: { text: "解决中", color: "warning" },
            resolved: { text: "已解决", color: "success" },
          };
          const config = statusMap[status as keyof typeof statusMap];
          return <Badge status={config.color as any} text={config.text} />;
        },
      },
      {
        title: "影响",
        dataIndex: "impact",
        key: "impact",
      },
      {
        title: "时间",
        dataIndex: "timestamp",
        key: "timestamp",
        render: (timestamp: Date) => dayjs(timestamp).format("MM-DD HH:mm"),
      },
      {
        title: "操作",
        key: "action",
        render: (_: any, record: SystemIssue) => (
          <Button
            type="link"
            size="small"
            onClick={() => {
              setSelectedIssue(record);
              setIssueModalVisible(true);
            }}
          >
            查看详情
          </Button>
        ),
      },
    ];

    return (
      <Table
        columns={columns}
        dataSource={systemIssues}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        size="small"
      />
    );
  };

  // 渲染登录尝试图表
  const renderLoginAttemptsChart = () => (
    <ResponsiveContainer width="100%" height={300}>
      <AreaChart data={securityMetrics.loginAttempts}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="date" />
        <YAxis />
        <RechartsTooltip />
        <Legend />
        <Area
          type="monotone"
          dataKey="attempts"
          stackId="1"
          stroke="#1890ff"
          fill="#1890ff"
          fillOpacity={0.3}
          name="总尝试次数"
        />
        <Area
          type="monotone"
          dataKey="failed"
          stackId="1"
          stroke="#ff4d4f"
          fill="#ff4d4f"
          fillOpacity={0.3}
          name="失败次数"
        />
        <Area
          type="monotone"
          dataKey="suspicious"
          stackId="1"
          stroke="#fa8c16"
          fill="#fa8c16"
          fillOpacity={0.3}
          name="可疑次数"
        />
      </AreaChart>
    </ResponsiveContainer>
  );

  // 渲染威胁分布图表
  const renderThreatDistributionChart = () => (
    <ResponsiveContainer width="100%" height={300}>
      <PieChart>
        <Pie
          data={securityMetrics.threatDistribution}
          cx="50%"
          cy="50%"
          labelLine={false}
          label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
          outerRadius={80}
          fill="#8884d8"
          dataKey="count"
        >
          {securityMetrics.threatDistribution.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={["#ff4d4f", "#fa8c16", "#eb2f96", "#722ed1", "#13c2c2"][index]} />
          ))}
        </Pie>
        <RechartsTooltip />
      </PieChart>
    </ResponsiveContainer>
  );

  // 渲染系统性能图表
  const renderSystemPerformanceChart = () => (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart data={securityMetrics.systemPerformance}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="time" />
        <YAxis />
        <RechartsTooltip />
        <Legend />
        <Line type="monotone" dataKey="cpu" stroke="#ff4d4f" name="CPU使用率" />
        <Line type="monotone" dataKey="memory" stroke="#1890ff" name="内存使用率" />
        <Line type="monotone" dataKey="disk" stroke="#52c41a" name="磁盘使用率" />
        <Line type="monotone" dataKey="network" stroke="#fa8c16" name="网络使用率" />
      </LineChart>
    </ResponsiveContainer>
  );

  return (
    <MonitoringContainer>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>AI安全监测中心</Title>
        <Text type="secondary">
          欢迎回来, {user?.name}! 今天是{dayjs().format("YYYY年MM月DD日")}
        </Text>
      </div>

      {/* 系统状态 */}
      <Alert
        message={`系统运行状态: 正常 健康度: ${stats.systemHealth}%`}
        type="success"
        showIcon
        style={{ marginBottom: 24 }}
        action={
          <Space>
            <Text>最后扫描: {dayjs(stats.lastScanTime).format("MM-DD HH:mm")}</Text>
            <Button
              type="primary"
              icon={scanning ? <LoadingOutlined /> : <SyncOutlined />}
              loading={scanning}
              onClick={performAIScan}
            >
              {scanning ? "AI扫描中..." : "启动AI扫描"}
            </Button>
          </Space>
        }
      />

      {/* 统计指标 */}
      {renderMetrics()}

      {/* 主要内容 */}
      <Tabs defaultActiveKey="overview" style={{ marginTop: 24 }}>
        <TabPane tab="安全概览" key="overview">
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={12}>
              <StyledCard title="登录尝试监控" extra={<EyeOutlined />}>
                {renderLoginAttemptsChart()}
              </StyledCard>
            </Col>
            <Col xs={24} lg={12}>
              <StyledCard title="威胁类型分布" extra={<PieChart />}>
                {renderThreatDistributionChart()}
              </StyledCard>
            </Col>
            <Col xs={24}>
              <StyledCard title="系统性能监控" extra={<DashboardOutlined />}>
                {renderSystemPerformanceChart()}
              </StyledCard>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="风险行为" key="risks">
          <StyledCard
            title="用户风险行为检测"
            extra={
              <Space>
                <Text type="secondary">共检测到 {riskBehaviors.length} 个风险行为</Text>
                <Button icon={<ReloadOutlined />} onClick={loadData}>
                  刷新
                </Button>
              </Space>
            }
          >
            {renderRiskBehaviorsTable()}
          </StyledCard>
        </TabPane>

        <TabPane tab="系统问题" key="issues">
          <StyledCard
            title="系统问题监控"
            extra={
              <Space>
                <Text type="secondary">共发现 {systemIssues.length} 个系统问题</Text>
                <Button icon={<ReloadOutlined />} onClick={loadData}>
                  刷新
                </Button>
              </Space>
            }
          >
            {renderSystemIssuesTable()}
          </StyledCard>
        </TabPane>

        <TabPane tab="AI分析报告" key="ai-report">
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={12}>
              <AIAnalysisCard title="AI安全分析">
                <Paragraph>
                  <strong>分析时间:</strong> {dayjs().format("YYYY-MM-DD HH:mm:ss")}
                </Paragraph>
                <Paragraph>
                  <strong>扫描范围:</strong> 用户行为、系统日志、网络流量、数据库访问
                </Paragraph>
                <Paragraph>
                  <strong>主要发现:</strong>
                </Paragraph>
                <ul>
                  <li>检测到 3 个高风险用户行为</li>
                  <li>系统性能指标正常，CPU使用率在合理范围内</li>
                  <li>网络流量模式正常，未发现异常连接</li>
                  <li>数据库访问模式符合预期</li>
                </ul>
                <Paragraph>
                  <strong>建议措施:</strong>
                </Paragraph>
                <ul>
                  <li>加强对高风险用户的监控</li>
                  <li>定期更新安全策略</li>
                  <li>优化系统性能监控</li>
                </ul>
              </AIAnalysisCard>
            </Col>
            <Col xs={24} lg={12}>
              <ThreatCard title="威胁情报">
                <Paragraph>
                  <strong>最新威胁:</strong>
                </Paragraph>
                <Timeline>
                  <Timeline.Item color="red">
                    <Text strong>检测到可疑登录尝试</Text>
                    <br />
                    <Text type="secondary">时间: {dayjs().subtract(2, "hours").format("HH:mm")}</Text>
                  </Timeline.Item>
                  <Timeline.Item color="orange">
                    <Text strong>系统资源使用异常</Text>
                    <br />
                    <Text type="secondary">时间: {dayjs().subtract(4, "hours").format("HH:mm")}</Text>
                  </Timeline.Item>
                  <Timeline.Item color="green">
                    <Text strong>安全扫描完成</Text>
                    <br />
                    <Text type="secondary">时间: {dayjs().subtract(6, "hours").format("HH:mm")}</Text>
                  </Timeline.Item>
                </Timeline>
              </ThreatCard>
            </Col>
          </Row>
        </TabPane>
      </Tabs>

      {/* 风险行为详情模态框 */}
      <Modal
        title="风险行为详情"
        visible={riskModalVisible}
        onCancel={() => setRiskModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedRisk && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="用户信息">
                {selectedRisk.userName} ({selectedRisk.userRole})
              </Descriptions.Item>
              <Descriptions.Item label="行为类型">
                <Tag color="red">{selectedRisk.behaviorType}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="风险等级">
                <RiskLevelTag color="red">{selectedRisk.riskLevel.toUpperCase()}</RiskLevelTag>
              </Descriptions.Item>
              <Descriptions.Item label="AI置信度">
                <Progress percent={selectedRisk.aiConfidence} status="active" />
              </Descriptions.Item>
              <Descriptions.Item label="描述">
                {selectedRisk.description}
              </Descriptions.Item>
              <Descriptions.Item label="建议措施">
                {selectedRisk.recommendedAction}
              </Descriptions.Item>
              <Descriptions.Item label="证据">
                <ul>
                  {selectedRisk.evidence.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>

      {/* 系统问题详情模态框 */}
      <Modal
        title="系统问题详情"
        visible={issueModalVisible}
        onCancel={() => setIssueModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedIssue && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="问题类型">
                <Tag color="red">{selectedIssue.type}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="严重程度">
                <RiskLevelTag color="red">{selectedIssue.severity.toUpperCase()}</RiskLevelTag>
              </Descriptions.Item>
              <Descriptions.Item label="标题">
                {selectedIssue.title}
              </Descriptions.Item>
              <Descriptions.Item label="描述">
                {selectedIssue.description}
              </Descriptions.Item>
              <Descriptions.Item label="影响">
                {selectedIssue.impact}
              </Descriptions.Item>
              <Descriptions.Item label="受影响组件">
                {selectedIssue.affectedComponents.join(", ")}
              </Descriptions.Item>
              <Descriptions.Item label="AI分析">
                {selectedIssue.aiAnalysis}
              </Descriptions.Item>
              <Descriptions.Item label="解决方案">
                {selectedIssue.resolution}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </MonitoringContainer>
  );
};

export default AdminAIMonitoring; 